#!/bin/bash
#
# Copyright 2015-2017 Adrian DC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# === Repo TWRP ===
function repotwrp()
{
  # Usage
  if [ -z "${1}" ]; then
    echo '';
    echo ' Usage: repotwrp {device} [nosync,nowipe,outcl,fota,local +fotareboot] (Advanced builder for TWRP)';
    echo '';
    return;
  fi;

  # Variables
  local PhoneName=${1};
  local BuildParams=${2};
  local CurDir;
  local RootDir;
  local TargetDir;

  # Access repo root
  CurDir=${PWD};
  croot;
  RootDir=$(pwd);

  # Sources Sync
  if [[ ! "${BuildParams}" == *'nosync'* ]]; then
    repo sync --current-branch --detach --force-broken --force-sync --no-clone-bundle --no-tags;
  fi;

  # Clean
  if [[ ! "${BuildParams}" == *'nowipe'* ]]; then
    make clean;

  # Cleanout
  elif [[ "${BuildParams}" == *'outcl'* ]]; then
    rm -rfv "./out/target/product/${PhoneName}/recovery/"*;
    rm -rfv "./out/target/product/${PhoneName}/root/"*;
  fi;

  # Handle boot types
  MultiROMBootableTWRP=true;
  case "${PhoneName}" in
    dora|kagura)
        MultiROMBootableTWRP=;;
  esac;

  # Make recovery
  source ./build/envsetup.sh;
  croot;
  lunch "omni_${PhoneName}-userdebug";
  makes recoveryimage "${RootDir}/out/target/product/${PhoneName}/system/build.prop";
  echo '';

  # Make releases
  echo '  [ Making release files ]';
  echo '';
  local TWRPVersion;
  TWRPVersion=$(grep '#define TW_MAIN_VERSION_STR' bootable/recovery/variables.h | sed 's/.*\"\(.*\)\".*/\1/' | cut -c 1-5);
  if [ -z "${TWRPVersion}" ]; then
    TWRPVersion=$(grep 'TW_VERSION_STR' bootable/recovery/variables.h | sed 's/.*\"\(.*\)\".*/\1/' | cut -c 1-5);
  fi;
  local TWRPImg=./out/target/product/${PhoneName}/recovery.img;
  local DateTag;
  DateTag=$(date +'%Y%m%d');
  local OutBootImg=twrp-${TWRPVersion}-${DateTag}-boot-${PhoneName}.img;
  local OutFOTAZip=twrp-${TWRPVersion}-${DateTag}-fota-${PhoneName}.zip;
  local OutMultiROMZip=twrp-${TWRPVersion}-${DateTag}-secondary-multirom-${PhoneName}.zip;
  local OutTWRP=twrp.img;
  TargetDir="$(desktoppath)/TWRP-Android";
  mkdir -p "${TargetDir}/";

  # Partitions
  local FOTAPartition;
  local SystemPartition;
  FOTAPartition=$(androiddevicestarget fota);
  SystemPartition=$(androiddevicestarget system);

  # Clean old releases
  rm -f "${TargetDir}/${OutTWRP}";
  rm -f "${TargetDir}/${OutBootImg}";
  rm -f "${TargetDir}/${OutMultiROMZip}";
  rm -f "${TargetDir}/${OutFOTAZip}";
  rm -f "${TargetDir}/${OutMultiROMZip}.unsigned.zip";
  rm -f "${TargetDir}/${OutFOTAZip}.unsigned.zip";

  # Missing built recovery
  if [ ! -f "${TWRPImg}" ]; then
    echo '';
    echo ' Error: Output files missing';
    echo '';
    cd "${CurDir}";
    return;
  fi;

  # Export TWRP images
  cp "${TWRPImg}" "${TargetDir}/${OutTWRP}";
  cp "${TWRPImg}" "${TargetDir}/${OutBootImg}";

  # Generate recovery zip, updater-script and recovery files
  cd "${TargetDir}/";
  mkdir -p ./META-INF/com/google/android/;
  cp "${ANDROID_DEVELOPMENT_SHELL_TOOLS_FLASHABLE_ANDROID_BASE}" "${TargetDir}/${OutFOTAZip}.unsigned.zip";
  cp "${ANDROID_DEVELOPMENT_SHELL_TOOLS_UPDATER_FLASH_FOTA}" ./META-INF/com/google/android/updater-script;
  sed -i "s/ANDROID_FOTA_PARTITION/${FOTAPartition//\//\\\/}/" ./META-INF/com/google/android/updater-script;
  zip -g "${TargetDir}/${OutFOTAZip}.unsigned.zip" ./META-INF/com/google/android/updater-script;
  zip -j -g "${TargetDir}/${OutFOTAZip}.unsigned.zip" "${TargetDir}/${OutTWRP}";
  rm -rf ./META-INF;

  # Generate secondary zip, updater-script and recovery files
  mkdir -p ./META-INF/com/google/android/;
  cp "${ANDROID_DEVELOPMENT_SHELL_TOOLS_FLASHABLE_ANDROID_BASE}" "${TargetDir}/${OutMultiROMZip}.unsigned.zip";
  cp "${ANDROID_DEVELOPMENT_SHELL_TOOLS_UPDATER_MULTIROM_SECONDARY}" ./META-INF/com/google/android/updater-script;
  sed -i "s/ANDROID_FOTA_PARTITION/${FOTAPartition//\//\\\/}/" ./META-INF/com/google/android/updater-script;
  sed -i "s/ANDROID_SYSTEM_PARTITION/${SystemPartition//\//\\\/}/" ./META-INF/com/google/android/updater-script;
  zip -g "${TargetDir}/${OutMultiROMZip}.unsigned.zip" ./META-INF/com/google/android/updater-script;
  zip -j -g "${TargetDir}/${OutMultiROMZip}.unsigned.zip" "${TargetDir}/${OutTWRP}";
  rm -rf ./META-INF;
  cd "${RootDir}/out/target/product/${PhoneName}/";
  zip -g "${TargetDir}/${OutMultiROMZip}.unsigned.zip" -r ./system/build.prop;

  # Zips signatures
  cd ../../../../;
  signzip "${TargetDir}/${OutFOTAZip}.unsigned.zip" "${TargetDir}/${OutFOTAZip}";
  signzip "${TargetDir}/${OutMultiROMZip}.unsigned.zip" "${TargetDir}/${OutMultiROMZip}";
  rm -f "${TargetDir}/${OutTWRP}";

  # Zips results
  echo '';
  echo -e " \e[1;37mPackage Boot File:\e[0m ${TargetDir}/${OutMultiROMZip}";
  echo -e " \e[1;37mPackage FOTA File:\e[0m ${TargetDir}/${OutFOTAZip}";
  echo '';

  # Flash new image
  echo '';
  echo "  [ Install TWRP on the '${PhoneName}' ]";
  echo '';
  echo -n '  Flash Recovery to FOTA (y/N) ? ';
  if [[ "${BuildParams}" == *'fota'* ]]; then
    key=y;
  else
    read -r -t 10 key;
  fi;
  if [[ "${key}" == 'y' || "${key}" == 'Y' ]] && [ -f "${TWRPImg}" ]; then
    echo '';
    adb root;
    adbwait;
    adb push "${TWRPImg}" /tmp/twrp.img;
    if [ ! -z "$(adb shell 'ls /system/bin/dd 2> /dev/null')" ]; then
      adb shell /system/bin/dd if=/tmp/twrp.img of="${FOTAPartition}";
    else
      adb shell /sbin/dd if=/tmp/twrp.img of="${FOTAPartition}";
    fi;
    if [[ "${BuildParams}" == *'fotareboot'* ]]; then
      adb reboot recovery;
    fi;
  else
    echo '';
  fi;

  # Upload new release
  local UploadFolder=${PhoneName^}/TWRP-Recovery;
  echo '';
  echo '';
  echo "  [ Publish online to '${UploadFolder}' ]";
  echo '';
  echo -n '  Upload (Y/n) ? ';
  local key;
  if [[ "${BuildParams}" == *'local'* ]]; then
    key=n;
  else
    read -r -t 30 key;
  fi;
  echo '';
  if [[ ! "${key}" == 'n' && ! "${key}" == 'N' ]]; then
    fileupl "${TargetDir}/${OutBootImg}" "${UploadFolder}";
    if [ ! -z "${MultiROMBootableTWRP}" ]; then
      fileupl "${TargetDir}/${OutMultiROMZip}" "${UploadFolder}";
    fi;
    fileupl "${TargetDir}/${OutFOTAZip}" "${UploadFolder}";
  fi;

  # End of work
  echo '';
  cd "${CurDir}";
}

# === Repo MultiROM ===
function repomrom()
{
  # Usage
  if [ -z "${1}" ]; then
    echo '';
    echo ' Usage: repomrom {device} [nosync,nowipe,outcl,fota,local +fotareboot] (Advanced builder for MultiROM)';
    echo '';
    return;
  fi;

  # Variables
  local PhoneName=${1};
  local BuildParams=${2};
  local CurDir;
  local RootDir;
  local TargetDir;

  # Access repo root
  CurDir=${PWD};
  croot;
  RootDir=$(pwd);

  # Handle boot types
  local MultiROMBootableTWRP;
  local MultiROMRecoveryInjector;
  local MultiROMUninstaller;

  # Configure devices
  case "${PhoneName}" in
    huashan|mint|hayabusa|tsubasa)
      MultiROMBootableTWRP=true;
      MultiROMRecoveryInjector=;
      MultiROMUninstaller=;;
    dora|kagura)
      MultiROMBootableTWRP=;
      MultiROMRecoveryInjector=true;
      MultiROMUninstaller=true;;
    *)
      MultiROMBootableTWRP=true;
      MultiROMRecoveryInjector=;
      MultiROMUninstaller=true;;
  esac;

  # Sources Sync
  if [[ ! "${BuildParams}" == *'nosync'* ]]; then
    repo sync --current-branch --detach --force-broken --force-sync --no-clone-bundle --no-tags;

    # MutiROM submodules
    cd ./system/extras/multirom/;
    git submodule update --init;
    git submodule update --force;
    cd ./../../../;
  fi;

  # Clean
  if [[ ! "${BuildParams}" == *'nowipe'* ]]; then
    make clean;

  # Cleanout
  elif [[ "${BuildParams}" == *'outcl'* ]]; then
    rm -rfv "./out/target/product/${PhoneName}/recovery/"*;
    rm -rfv "./out/target/product/${PhoneName}/root/"*;
  fi;

  # Make recovery
  source ./build/envsetup.sh;
  if [[ ! "${BuildParams}" == *'nobuild'* ]]; then
    rm -rf "${BuildDir}/multirom"*;

    # Build
    lunch "omni_${PhoneName}-userdebug";
    if [[ "${BuildParams}" == *'kernel'* ]]; then
      makes multirom_kernel_zip;
    else
      makes recoveryimage multirom trampoline multirom_zip multirom_uninstaller multirom_recovery_injector_zip;
    fi;
  else
    echo 'Build skipped...';
  fi;
  echo '';

  # Make releases
  echo '  [ Making release files ]';
  echo '';
  local TWRPImg=./out/target/product/${PhoneName}/recovery.img;
  local DateTag;
  DateTag=$(date +'%Y%m%d');
  TargetDir=$(desktoppath);
  local BuildDir=./out/target/product/${PhoneName};
  cp "${BuildDir}/obj/ETC/system_build_prop_intermediates/build.prop" "${BuildDir}/system/build.prop";

  # Partitions
  local FOTAPartition;
  local SystemPartition;
  FOTAPartition=$(androiddevicestarget fota);
  SystemPartition=$(androiddevicestarget system);

  # Built files
  local BuiltInstaller="multirom-*-v33x-UNOFFICIAL-${PhoneName}.zip";
  local BuiltKernel="multirom_kernel-*-v33x-UNOFFICIAL-${PhoneName}.zip";
  local BuiltRecovery=recovery.img;
  local BuiltRecoveryInjector=multirom_recovery_injector.zip;
  local BuiltUninstaller=multirom_uninstaller.zip;

  # Published files
  local PublishDir=MultiROM-Android;
  local PublishInstaller=${PublishDir}/multirom-${DateTag}-v33x-${PhoneName}.zip;
  local PublishKernel;
  if [ ! -z "${3}" ]; then
    PublishKernel=${PublishDir}/kernel-${DateTag}-${PhoneName}-${3}.zip;
  else
    PublishKernel=${PublishDir}/kernel-${DateTag}-${PhoneName}.zip;
  fi;
  local PublishRecoveryFOTA=${PublishDir}/multirom-${DateTag}-recovery-fota-${PhoneName}.zip;
  local PublishRecoveryMultiROM=${PublishDir}/multirom-${DateTag}-recovery-secondary-${PhoneName}.zip;
  local PublishRecoveryInjector=${PublishDir}/multirom-${DateTag}-recovery-injector-${PhoneName}.zip;
  local PublishUninstaller=${PublishDir}/multirom-${DateTag}-uninstaller-${PhoneName}.zip;

  # Missing built recovery
  if [ ! -f "${BuildDir}/${BuiltRecovery}" ]; then
    echo '';
    echo ' Error: Output files missing';
    echo '';
    cd "${CurDir}";
    return;
  fi;

  if [ ! -d "${TargetDir}/${PublishDir}" ]; then
    mkdir -p "${TargetDir}/${PublishDir}";
  fi;

  BuiltInstaller=$(find "${BuildDir}" -maxdepth 1 -name "${BuiltInstaller}" -print \
                 | tail -n 1);
  if [ ! -z "${BuiltInstaller}" ]; then
    cp -f "${BuiltInstaller}" "${TargetDir}/${PublishInstaller}.unsigned.zip";
    signzip "${TargetDir}/${PublishInstaller}.unsigned.zip" "${TargetDir}/${PublishInstaller}";
  fi;

  BuiltKernel=$(find "${BuildDir}" -maxdepth 1 -name "${BuiltKernel}" -print);
  if [ ! -z "${BuiltKernel}" ]; then
    cp -f "${BuiltKernel}" "${TargetDir}/${PublishKernel}.unsigned.zip";
    signzip "${TargetDir}/${PublishKernel}.unsigned.zip" "${TargetDir}/${PublishKernel}";
  fi;

  if [ -f "${BuildDir}/${BuiltUninstaller}" ]; then
    cp -f "${BuildDir}/${BuiltUninstaller}" "${TargetDir}/${PublishUninstaller}.unsigned.zip";
    signzip "${TargetDir}/${PublishUninstaller}.unsigned.zip" "${TargetDir}/${PublishUninstaller}";
  fi;

  if [ -f "${BuildDir}/${BuiltRecovery}" ]; then
    cp "${BuildDir}/${BuiltRecovery}" "${TargetDir}/twrp.img";
    if [ -f "${TargetDir}/${PublishRecoveryFOTA}" ]; then rm -f "${TargetDir}/${PublishRecoveryFOTA}"; fi;
    if [ -f "${TargetDir}/${PublishRecoveryMultiROM}" ]; then rm -f "${TargetDir}/${PublishRecoveryMultiROM}"; fi;

    # Generate recovery zip, updater-script and recovery files
    cd "${TargetDir}/${PublishDir}";
    mkdir -p ./META-INF/com/google/android/;
    cp "${ANDROID_DEVELOPMENT_SHELL_TOOLS_FLASHABLE_ANDROID_BASE}" "${TargetDir}/${PublishRecoveryFOTA}.unsigned.zip";
    cp "${ANDROID_DEVELOPMENT_SHELL_TOOLS_UPDATER_FLASH_FOTA}" ./META-INF/com/google/android/updater-script;
    sed -i "s/ANDROID_FOTA_PARTITION/${FOTAPartition//\//\\\/}/" ./META-INF/com/google/android/updater-script;
    zip -g "${TargetDir}/${PublishRecoveryFOTA}.unsigned.zip" ./META-INF/com/google/android/updater-script;
    zip -j -g "${TargetDir}/${PublishRecoveryFOTA}.unsigned.zip" "${TargetDir}/twrp.img";
    rm -rf ./META-INF;

    # Generate secondary zip, updater-script and recovery files
    mkdir -p ./META-INF/com/google/android/;
    cp "${ANDROID_DEVELOPMENT_SHELL_TOOLS_FLASHABLE_ANDROID_BASE}" "${TargetDir}/${PublishRecoveryMultiROM}.unsigned.zip";
    cp "${ANDROID_DEVELOPMENT_SHELL_TOOLS_UPDATER_MULTIROM_SECONDARY}" ./META-INF/com/google/android/updater-script;
    sed -i "s/ANDROID_FOTA_PARTITION/${FOTAPartition//\//\\\/}/" ./META-INF/com/google/android/updater-script;
    sed -i "s/ANDROID_SYSTEM_PARTITION/${SystemPartition//\//\\\/}/" ./META-INF/com/google/android/updater-script;
    zip -g "${TargetDir}/${PublishRecoveryMultiROM}.unsigned.zip" ./META-INF/com/google/android/updater-script;
    zip -j -g "${TargetDir}/${PublishRecoveryMultiROM}.unsigned.zip" "${TargetDir}/twrp.img";
    rm -rf ./META-INF;
    cd "${RootDir}/out/target/product/${PhoneName}/";
    zip -g "${TargetDir}/${PublishRecoveryMultiROM}.unsigned.zip" -r ./system/build.prop;

    # Zips signatures
    cd ../../../../;
    signzip "${TargetDir}/${PublishRecoveryFOTA}.unsigned.zip" "${TargetDir}/${PublishRecoveryFOTA}";
    signzip "${TargetDir}/${PublishRecoveryMultiROM}.unsigned.zip" "${TargetDir}/${PublishRecoveryMultiROM}";
    rm -f "${TargetDir}/twrp.img";
  fi;

  rm -f "${TargetDir}/${PublishRecoveryInjector}";
  if [ -f "${BuildDir}/${BuiltRecoveryInjector}" ]; then
    cp "${BuildDir}/${BuiltRecoveryInjector}" "${TargetDir}/${PublishRecoveryInjector}";
  fi;

  echo '';
  echo -e " \e[1;37mInstaller File:\e[0m ${PublishInstaller}";
  echo -e " \e[1;37mUninstaller File:\e[0m ${PublishUninstaller}";
  echo -e " \e[1;37mRecovery Boot File:\e[0m ${PublishRecoveryMultiROM}";
  echo -e " \e[1;37mRecovery FOTA File:\e[0m ${PublishRecoveryFOTA}";
  echo -e " \e[1;37mRecovery Injector File:\e[0m ${PublishRecoveryInjector}";
  echo -e " \e[1;37mKernel File:\e[0m ${PublishKernel}";
  echo '';

  # Flash new image
  echo '';
  echo "  [ Install Recovery on the '${PhoneName}' ]";
  echo '';
  echo -n '  Flash Recovery to FOTA (y/N) ? ';
  local  key
  if [[ "${BuildParams}" == *'fota'* ]]; then
    key=y;
  else
    read -r -t 10 key;
  fi;
  if [[ "${key}" == 'y' || "${key}" == 'Y' ]] && [ -f "${TWRPImg}" ]; then
    echo '';
    adb root;
    adbwait;
    adb push "${TWRPImg}" /tmp/twrp.img;
    if [ ! -z "$(adb shell 'ls /system/bin/dd 2> /dev/null')" ]; then
      adb shell /system/bin/dd if=/tmp/twrp.img of="${FOTAPartition}";
    else
      adb shell /sbin/dd if=/tmp/twrp.img of="${FOTAPartition}";
    fi;
    if [[ "${BuildParams}" == *'fotareboot'* ]]; then
      adb reboot recovery;
    fi;
  else
    echo '';
  fi;

  # Upload new release
  local UploadFolder=${PhoneName^}/MultiROM-Android;
  echo '';
  echo '';
  echo "  [ Publish online to '${UploadFolder}' ]";
  echo '';
  echo -n '  Upload (Y/n) ? ';
  local key;
  if [[ "${BuildParams}" == *'local'* ]]; then
    key=n;
  else
    read -r -t 30 key;
  fi;
  echo '';
  if [[ ! "${key}" == 'n' && ! "${key}" == 'N' ]]; then
    fileupl "${TargetDir}/${PublishInstaller}" "${UploadFolder}";
    if [ ! -z "${MultiROMBootableTWRP}" ]; then
      fileupl "${TargetDir}/${PublishRecoveryMultiROM}" "${UploadFolder}";
    fi;
    if [ ! -z "${MultiROMRecoveryInjector}" ]; then
      fileupl "${TargetDir}/${PublishRecoveryInjector}" "${UploadFolder}";
    fi;
    if [ ! -z "${MultiROMUninstaller}" ]; then
      fileupl "${TargetDir}/${PublishUninstaller}" "${UploadFolder}";
    fi;
    fileupl "${TargetDir}/${PublishRecoveryFOTA}" "${UploadFolder}";
  fi;

  # End of work
  echo '';
  cd "${CurDir}";
}
